﻿using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;


namespace Faust.Andrew.MTG.Helper
{
    public static class Utility
    {
        public static double DegreesToRadians(double angle)
        {
            return (Math.PI * angle) / 180.0;
        }

        //calculate hypotenuse using pythagorean theorem
        public static double CalculatePythagorean(double a, double b)
        {
            return System.Math.Sqrt((a * a) + (b * b));
        }

        public static ImageSource ToImageSource(this System.Drawing.Bitmap bitmap)
        {
            return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),
                IntPtr.Zero,
                System.Windows.Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
        }

        public static RenderTargetBitmap ToBitmapSource(this FrameworkElement target)
        {
            int width = (int)target.ActualWidth;
            int height = (int)target.ActualHeight;

            Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
            RenderTargetBitmap renderBitmap
            = new RenderTargetBitmap(width,
            height,
            96, 96,
            PixelFormats.Pbgra32);

            DrawingVisual visual = new DrawingVisual();
            using (DrawingContext context = visual.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(target);
                context.DrawRectangle(brush,
                null,
                new Rect(new Point(), bounds.Size));
            }

            renderBitmap.Render(visual);
            return renderBitmap;
        }

        public static RenderTargetBitmap Zoom(this ImageSource source, double zoomLevel)
        {
            int newWidth = (int)(source.Width * zoomLevel);
            int newHeight = (int)(source.Height * zoomLevel);

            // Target Rect for the resize operation
            Rect rect = new Rect(0, 0, newWidth, newHeight);

            // Create a DrawingVisual/Context to render with
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                drawingContext.DrawImage(source, rect);
            }

            // Use RenderTargetBitmap to resize the original image
            RenderTargetBitmap resizedImage = new RenderTargetBitmap(
                (int)rect.Width, (int)rect.Height,  // Resized dimensions
                96, 96,                             // Default DPI values
                PixelFormats.Default);              // Default pixel format            
            resizedImage.Render(drawingVisual);

            // Return the resized image
            return resizedImage;
        }
    }
}
